import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select, Alert,
  Menu, Dropdown,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import BuildModalTitle from '@/components/BuildModalTitle';
import mail from './../../images/mail.png';
import mailOpen from './../../images/mail-open.png';
import liuliangji from './../../images/liuliangji.png';
import AddOrEditMeter from './addOrEditUser';
import AlarmSetting from './AlarmSetting';
import ValveData from './ValveData';
import ValveData2 from './ValveData2';
import ValveData3 from './ValveData3';
import ValveData4 from './ValveData4';
import ValveData5 from './ValveData5';
import ValveData6 from './ValveData6';
import styles from './index.less';
import gold_groud from './../../images/valve_small.png';
import shuizhi from './../../images/shuizhi.png';
import dcjlq from './../../images/dcjlq.jpg';
import gold_groud2 from './../../images/valve2_small.jpg';
import DN800SNLD from './../../images/DN800SNLD.jpg';
import DN800unknow from './../../images/DN800unknow.jpg';
import unknow from './../../images/unknow.png';
import LDE from './../../images/LDE.jpg';

const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ valve_flowmeter_site, loading, global }) => ({
  valve_flowmeter_site,
  global,
  loading: loading.models.valve_flowmeter_site,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      valve_flowmeter_site: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.img-data-content');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        valve_flowmeter_site: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'valve_flowmeter_site/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'valve_flowmeter_site/changeLoaded',
          });
          dispatch({
            type: 'valve_flowmeter_site/changeTableY',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'valve_flowmeter_site/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'valve_flowmeter_site/changeTableY',
    });
  };


  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.img-data-content');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'valve_flowmeter_site/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      valve_flowmeter_site: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem>
          <FormItem label="站点名称">
            {getFieldDecorator('name', {
              initialValue: searchParams.name,
            })(<Input style={{ width: '150px' }} placeholder="请输入" onKeyPress={this.keyPress}/>)}
          </FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>

      </Form>
    );
  }

  keyPress = (e) => {
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press');
      const {
        valve_flowmeter_site: { searchParams },
      } = this.props;
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;

        this.handleSearch({
          page: 1,
          per_page: searchParams.per_page,
          ...fieldsValue,
        });

      });
    }
  };

  handleAdd = () => {
    const location = this.findChildLocation();
    const config = JSON.parse(JSON.stringify(this.findChildConfig()));
    console.log('config', config);
    console.log('location', location);
    const formValues = this.AddForm.props.form.getFieldsValue();
    config.hardware_configs.device[0].upload_interval = config.hardware_configs.device[0].upload_interval * 60;
    config.hardware_configs.modbus = config.hardware_configs.modbus_03;
    if (config.hardware_configs.sensor) {
      for (let i = 0; i < config.hardware_configs.sensor.length; i++) {
        if (config.hardware_configs.sensor[i] && config.hardware_configs.sensor[i].type !== 0) {
          config.hardware_configs.sensor[i].over_cancel = config.hardware_configs.sensor[i].over;
          config.hardware_configs.sensor[i].under_cancel = config.hardware_configs.sensor[i].under;
        }

      }
    }
    console.log('formValues', formValues);

    if (config.template === 1 || config.template === 3 || config.template === 4 || config.template === 5
      || config.template === 6 || config.template === 7) {
      formValues.type = 1;
      config.hardware_configs.flowmeter = [{}, {}];
      config.hardware_configs.flowmeter[0].enable = 0;
      config.hardware_configs.flowmeter[1].enable = 0;
    } else {
      formValues.type = 2;
    }
    console.log('config', config);
    const that = this;
    this.props.dispatch({
      type: 'valve_flowmeter_site/add',
      payload: {
        ...formValues,
        longitude: location[0],
        latitude: location[1],
        ...config,
      },
      callback() {
        message.success('添加站点成功');
        that.setState({
          addModal: false,
        });
        const {
          valve_flowmeter_site: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };


  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      name: '',
      page: 1,
      per_page: 30,
    });
  };

  handleEdit = () => {
    const config = JSON.parse(JSON.stringify(this.findChildConfig()));
    console.log('config', config);
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const location = this.findChildLocation();
    console.log('location', location);
    config.hardware_configs.device[0].upload_interval = config.hardware_configs.device[0].upload_interval * 60;
    config.hardware_configs.modbus = config.hardware_configs.modbus_03;
    if (config.hardware_configs.sensor) {
      for (let i = 0; i < config.hardware_configs.sensor.length; i++) {
        if (config.hardware_configs.sensor[i] && config.hardware_configs.sensor[i].type !== 0) {
          config.hardware_configs.sensor[i].over_cancel = config.hardware_configs.sensor[i].over;
          config.hardware_configs.sensor[i].under_cancel = config.hardware_configs.sensor[i].under;
        }

      }
    }
    if (config.template === 1) {
      config.hardware_configs.flowmeter = [{}, {}];
      config.hardware_configs.flowmeter[0].enable = 0;
      config.hardware_configs.flowmeter[1].enable = 0;
    } else {
    }
    console.log('config', config);
    const that = this;
    this.props.dispatch({
      type: `valve_flowmeter_site/edit`,
      payload: {
        ...formValues,
        longitude: location[0],
        latitude: location[1],
        id: this.state.editRecord.id,
        ...config,
      },
      callback() {
        message.success('修改站点成功');
        that.setState({
          editModal: false,
        });
        const {
          valve_flowmeter_site: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `valve_flowmeter_site/remove`,
      payload: { id },
      callback: () => {
        message.success('删除站点成功');
        const {
          valve_flowmeter_site: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  getConfigFunc = (cb) => {
    this.findChildConfig = cb;
  };
  findChildFunc = (cb) => {
    this.findChildLocation = cb;
  };
  handleEditAlarm = () => {
    const formValues = this.AlarmForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    if (formValues.administrators_arr) {
      formValues.administrators = formValues.administrators_arr.map((item, index) => {
        return { id: item };
      });
    }
    this.props.dispatch({
      type: `valve_flowmeter_site/editAlarm`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('修改微信报警成功');
        that.setState({
          alarmModal: false,
        });
        const {
          valve_flowmeter_site: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  render() {
    const that = this;
    const {
      valve_flowmeter_site: { data, loading, tableY, meta, searchParams, selectedRowKeys },
      global: { gridTableW },
    } = this.props;
    console.log('data', data);
    const username=sessionStorage.getItem('username')

    const renderMenu = (item) => (
      <Menu>
        <Menu.Item onClick={(e) => {
          that.setState({
            editRecord: item,
            alarmModal: true,
          });
        }}>
         <span>
             报警设置
          </span>
        </Menu.Item>
        <Menu.Item onClick={(e) => {
          confirm({
            title: `确定要删除‘${item.name}’吗?`,
            content: '请谨慎操作！',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            centered: true,
            maskClosable: true,
            onOk() {
              that.handleDelete(item.id);
            },
            onCancel() {
              console.log('Cancel');
            },
          });
        }}>
         <span>
             删除
          </span>
        </Menu.Item>
      </Menu>
    );

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>水务监控站点</span>
      </div>
      <div className="table-page">
        <div className="table-searchWithInfo2">

          {this.renderSimpleForm()}
          <div className="table-info2">
            {
              find(this.permissions, { name: 'workstation_operation' }) &&
              <div className="table-info-item2" style={{ cursor: 'pointer' }} onClick={() => {
                this.setState({
                  addModal: true,
                });
              }}>
                <p><Icon type={'plus'}></Icon></p>
                <p>添加站点</p>
              </div>
            }

            <div className="table-info-item2">
              <p>{meta.total}</p>
              <p>站点数量</p>
            </div>
          </div>
        </div>
        <div>
          <Row className={'img-data-content'} gutter={[16, 16]}
               style={{ height: tableY + 'px', maxHeight: tableY + 'px', overflow: 'auto', overflowX: 'hidden' }}>
            {
              data.map((item, index) => {
                let borderTopColor = '#5e83bf';
                switch (index % 4) {
                  case 0:
                    borderTopColor = '#e77338';
                    break;
                  case 1:
                    borderTopColor = '#5e83bf';
                    break;
                  case 2:
                    borderTopColor = '#31b77d';
                    break;
                  case 3:
                    borderTopColor = '#C790E1';
                    break;

                }
                let statusText = '';
                if (item.online_status === 1) {
                  statusText = <span style={{ background: '#00b209', padding: '1px 4px', color: '#fff' }}>在线</span>;
                } else if (item.online_status === -1) {
                  statusText = <span style={{ background: 'red', padding: '1px 4px', color: '#fff' }}>离线</span>;
                }
                let alarmText = '';
                if (item.alarm === 0) {
                  alarmText = <span style={{ background: '#00b209', padding: '1px 4px', color: '#fff' }}>正常</span>;
                } else if (item.alarm === 1) {
                  alarmText = <span className={styles.alarm} style={{ padding: '1px 4px', color: '#fff' }}>报警</span>;
                }
                let template = '未知';
                if (item.template === 1) {
                  template = '双阀减压阀站点';
                } else if (item.template === 2) {
                  template = '流量计站点';
                } else if (item.template === 3) {
                  template = '水质检测站点';
                } else if (item.template === 4) {
                  template = '电磁计量器站点';
                }else if (item.template === 5) {
                  template = 'DN800电磁流量计(SNLD-DN800)';
                }else if (item.template === 6) {
                  template = 'DN800电磁流量计(未知)';
                }else if (item.template === 7) {
                  template = 'LDE-DN400-400(珠华)';
                }
                let locationImage = unknow;
                if (item.template === 1) {
                  locationImage = gold_groud2;
                } else if (item.template === 2) {
                  locationImage = liuliangji;
                } else if (item.template === 3) {
                  locationImage = shuizhi;
                } else if (item.template === 4) {
                  locationImage = dcjlq;
                } else if (item.template === 5) {
                  locationImage = DN800SNLD;
                } else if (item.template === 6) {
                  locationImage = DN800unknow;
                }else if (item.template === 7) {
                  locationImage = LDE;
                }

                return <Col className="gutter-row" md={6} lg={6} xl={6} xxl={4} key={index}>
                  <div className={styles.img_box} style={{ borderTopColor: borderTopColor }}>
                    <img style={{ cursor: 'pointer' }} onClick={() => {
                      this.setState({
                        editRecord: item,
                        dataModal: true,
                        name: item.name,

                      });
                    }} src={locationImage} alt=""/>
                    <h4>站点名称 : {item.name}</h4>
                    <h4>在线状态 : {statusText}</h4>
                    <h4>是否报警 : {alarmText}</h4>
                    <div className={styles.card_type}>
                      {template}
                    </div>
                    <div className={styles.card_action}>
                      <div onClick={() => {
                        this.setState({
                          editRecord: item,
                          dataModal: true,
                          name: item.name,
                        });
                      }}>数据
                      </div>
                      {
                        find(that.permissions, { name: 'workstation_operation' }) &&
                        <Fragment>
                          <div onClick={() => {
                            that.setState({
                              editRecord: item,
                              editModal: true,
                            });
                          }}>修改
                          </div>
                          <Dropdown overlay={renderMenu(item)}>
                            <div>更多</div>
                          </Dropdown>
                        </Fragment>

                      }

                    </div>
                  </div>
                </Col>;
              })
            }
          </Row>

          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Drawer
        title={`添加站点`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            addModal: false,
            editRecord: {},
          });
        }}
        width={700}
        keyboard={false}
        visible={this.state.addModal}
      >
        <AddOrEditMeter
          onClose={() => {
            this.setState({
              addModal: false,
              editRecord: {},
            });
          }}
          getConfigFunc={this.getConfigFunc}
          findChildFunc={this.findChildFunc}
          onSave={this.handleAdd}
          wrappedComponentRef={(inst) => this.AddForm = inst}
        />
      </Drawer>
      <Drawer
        title={`修改站点 ${this.state.editRecord.name} `}
        placement="right"
        destroyOnClose
        keyboard={false}
        onClose={() => {
          this.setState({
            editModal: false,
            editRecord: {},
          });
        }}
        width={700}
        visible={this.state.editModal}
      >
        <AddOrEditMeter
          onClose={() => {
            this.setState({
              editModal: false,
              editRecord: {},
            });
          }}
          editRecord={this.state.editRecord}
          getConfigFunc={this.getConfigFunc}
          findChildFunc={this.findChildFunc}
          onSave={this.handleEdit}
          name={this.state.name}
          wrappedComponentRef={(inst) => this.EditForm = inst}
        />
      </Drawer>
      {/*    <Drawer
        title={`设置站点 ${this.state.editRecord.name} `}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            setModal: false,
            editRecord: {},
          });
        }}
        width={700}
        keyboard={false}
        visible={this.state.setModal}
      >
        <SiteSetting
          onClose={() => {
            this.setState({
              setModal: false,
              editRecord: {},
            });
          }}
          onSearch={()=>{
            const {
              valve_flowmeter_site: { searchParams },
            } = that.props;
            that.handleSearch(searchParams);
          }}
          editRecord={this.state.editRecord}
          name={this.state.name}
          wrappedComponentRef={(inst) => this.EditForm = inst}
        />
      </Drawer>*/}
      <Modal
        title={<BuildModalTitle visible={this.state.dataModal} modalClass="dataModal"
                                title={`${this.state.editRecord.name} 数据`}/>}
        destroyOnClose
        onCancel={() => {
          this.setState({
            dataModal: false,
            editRecord: {},
          });
        }}
        width={1100}
        centered
        className="dataModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        visible={this.state.dataModal}
        footer={null}
      >
        {
          this.state.editRecord.online_status === -1 &&
          <Alert message="站点设备当前离线" type="error"/>
        }

        {
          this.state.editRecord &&
          this.state.editRecord.template === 1 &&
          <ValveData
            editRecord={this.state.editRecord}
            name={this.state.name}
            wrappedComponentRef={(inst) => this.dataForm = inst}
          />
        }
        {
          this.state.editRecord &&
          this.state.editRecord.template === 2 &&
          <ValveData2
            editRecord={this.state.editRecord}
            name={this.state.name}
            wrappedComponentRef={(inst) => this.dataForm = inst}
          />
        }
        {
          this.state.editRecord &&
          this.state.editRecord.template === 3 &&
          <ValveData3
            editRecord={this.state.editRecord}
            name={this.state.name}
            wrappedComponentRef={(inst) => this.dataForm = inst}
          />
        }
        {
          this.state.editRecord &&
          this.state.editRecord.template === 4 &&
          <ValveData4
            editRecord={this.state.editRecord}
            name={this.state.name}
            wrappedComponentRef={(inst) => this.dataForm = inst}
          />
        }
        {
          this.state.editRecord &&
          this.state.editRecord.template === 5 &&
          <ValveData5
            editRecord={this.state.editRecord}
            name={this.state.name}
            wrappedComponentRef={(inst) => this.dataForm = inst}
          />
        }
        {
          this.state.editRecord &&
          this.state.editRecord.template === 6 &&
          <ValveData6
            editRecord={this.state.editRecord}
            name={this.state.name}
            wrappedComponentRef={(inst) => this.dataForm = inst}
          />
        }
        {
          this.state.editRecord &&
          this.state.editRecord.template === 7 &&
          <ValveData5
            editRecord={this.state.editRecord}
            name={this.state.name}
            wrappedComponentRef={(inst) => this.dataForm = inst}
          />
        }
      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.alarmModal} modalClass="alarmModal"
                                title={`${this.state.editRecord.name} 微信报警设置`}/>}
        destroyOnClose
        onCancel={() => {
          this.setState({
            alarmModal: false,
            editRecord: {},
          });
        }}
        width={700}
        centered
        className="alarmModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        visible={this.state.alarmModal}
        onOk={this.handleEditAlarm}

      >
        <AlarmSetting
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.AlarmForm = inst}
        />
      </Modal>
    </div>;
  }
}

export default BasicList;
